const { Project, Section, Form } = require('../models');
const { buildPaginationResponse } = require('../middleware/pagination');

// 获取项目列表
const getProjects = async (req, res) => {
  try {
    const { status, createdBy, sort = '-createTime', isTemplate, search, name } = req.query;
    const { skip, limit } = req.pagination;

    // 构建查询条件
    const query = {};
    if (status) query.status = status;
    if (createdBy) query.createdBy = createdBy;
    if (isTemplate !== undefined) {
      // 前端可能传入 'true' 或 'false'，当为 false 时返回“非模板”（包含未设置 isTemplate 的历史数据）
      if (isTemplate === 'true') {
        query.isTemplate = true;
      } else if (isTemplate === 'false') {
        query.isTemplate = { $ne: true };
      }
    }
    // 关键词按项目名称模糊匹配
    const keyword = (search || name || '').trim();
    if (keyword) {
      query.name = { $regex: keyword, $options: 'i' };
    }

    // 执行查询
    const [projects, total] = await Promise.all([
      Project.find(query)
        .sort(sort)
        .skip(skip)
        .limit(limit)
        .populate('createdBy', 'username profile.firstName profile.lastName')
        .populate('updatedBy', 'username profile.firstName profile.lastName')
        .populate({
          path: 'configSections.sectionId',
          model: 'Section',
          select: 'name description isTemplate config'
        }),
      Project.countDocuments(query)
    ]);

    res.json({
      success: true,
      ...buildPaginationResponse(projects, total, req)
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取项目列表失败',
      error: error.message
    });
  }
};

// 获取项目详情
const getProject = async (req, res) => {
  try {
    const { id } = req.params;
    
    const project = await Project.findById(id)
      .populate('createdBy', 'username profile.firstName profile.lastName')
      .populate('updatedBy', 'username profile.firstName profile.lastName')
      .populate({
        path: 'configSections.sectionId',
        model: 'Section',
        select: 'name description isTemplate config forms',
        populate: {
          path: 'forms',
          model: 'Form',
          select: 'name code order description type config'
        }
      });

    if (!project) {
      return res.status(404).json({
        success: false,
        message: '项目未找到'
      });
    }

    res.json({
      success: true,
      data: project
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取项目详情失败',
      error: error.message
    });
  }
};

// 获取项目完整配置（包含所有章节、表单、字段）
const getProjectConfig = async (req, res) => {
  try {
    const { id } = req.params;
    
    const project = await Project.findById(id);
    
    if (!project) {
      return res.status(404).json({
        success: false,
        message: '项目未找到'
      });
    }

    // 获取项目配置的章节
    const configSections = [];
    
    if (project.configSections && project.configSections.length > 0) {
      // 按顺序获取章节
      const sortedSections = project.configSections.sort((a, b) => a.order - b.order);
      
      for (const sectionConfig of sortedSections) {
        const section = await Section.findById(sectionConfig.sectionId)
          .populate({
            path: 'forms',
            options: { sort: { order: 1 } }
          });
        
        if (section) {
          configSections.push({
            _id: section._id,
            name: section.name,
            order: sectionConfig.order,
            description: section.description,
            config: {
              ...section.config,
              ...sectionConfig.config  // 项目特定配置覆盖
            },
            forms: section.forms.map(form => ({
              _id: form._id,
              name: form.name,
              code: form.code,
              order: form.order,
              description: form.description,
              type: form.type,
              config: form.config
            }))
          });
        }
      }
    }

    // 构建完整的配置结构
    const configData = {
      _id: project._id,
      name: project.name,
      protocolNumber: project.protocolNumber,
      version: project.version,
      versionDate: project.versionDate,
      status: project.status,
      description: project.description,
      createTime: project.createTime,
      updateTime: project.updateTime,
      config: project.config,
      configSections: configSections
    };

    res.json({
      success: true,
      data: configData
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取项目配置失败',
      error: error.message
    });
  }
};

// 创建项目
const createProject = async (req, res) => {
  try {
    const { template, configSections, isTemplate, ...projectData } = req.body;
    console.log('创建项目请求:', req.body);
    // 基本项目数据（排除configSections，稍后单独处理）
    const basicProjectData = {
      ...projectData,
      isTemplate: isTemplate || false,
      createdBy: req.user._id,
      updatedBy: req.user._id
    };

    console.log('基本项目数据:', basicProjectData);

    // 创建项目
    const project = new Project(basicProjectData);
    await project.save();

    // 处理章节配置（优先使用直接传递的configSections，然后处理模板）
    if (configSections && configSections.length > 0) {
      // 分支一：传入 configSections（基于模板章节ID）——改为克隆模式
      const newConfigSections = [];

      const generateUniqueFormCode = (name = 'FORM') => {
        return `${name.toUpperCase().replace(/\s+/g, '_')}_${Date.now()}_${Math.floor(Math.random() * 10000)}`;
      };

      // 先遍历收集模板表单code，做去重后生成新表单，仅克隆一次
      const codeToNewFormId = new Map();
      const codeToNewCode = new Map();

      for (let i = 0; i < configSections.length; i++) {
        const { sectionId, order, config: sectionConfig = {} } = configSections[i];

        const sectionDoc = await Section.findById(sectionId).populate({ path: 'forms', model: 'Form' });
        console.log('sectionDoc', sectionDoc,!sectionDoc.isTemplate);
        if (!sectionDoc) {
          return res.status(400).json({ success: false, message: `模板章节不存在或无效: ${sectionId}` });
        }

        // 克隆章节
        const newSection = new Section({
          name: sectionDoc.name,
          order: order || i + 1,
          description: sectionDoc.description,
          forms: [],
          isTemplate: false,
          config: sectionDoc.config || {}
        });
        await newSection.save();

        // 克隆表单（去重：同模板code只克隆一次，其它访视复用该表单）
        if (Array.isArray(sectionDoc.forms) && sectionDoc.forms.length > 0) {
          for (const sourceForm of sectionDoc.forms) {
            const tplCode = sourceForm.code || 'FORM';
            let newFormId = codeToNewFormId.get(tplCode);
            if (!newFormId) {
              // 第一次遇到该模板code，创建新表单
              let clonedFields = [];
              if (sourceForm.config && Array.isArray(sourceForm.config.fields)) {
                clonedFields = sourceForm.config.fields.map((f) => ({
                  ...JSON.parse(JSON.stringify(f)),
                  id: f.id || require('uuid').v4(),
                  metadata: {
                    createdAt: new Date(),
                    updatedAt: new Date(),
                    version: 1,
                  },
                }));
              }

              // 生成映射的新code，避免与模板/全局冲突
              const mappedCode = codeToNewCode.get(tplCode) || generateUniqueFormCode('FORM');
              codeToNewCode.set(tplCode, mappedCode);

              const newForm = new Form({
                name: sourceForm.name,
                code: mappedCode,
                order: sourceForm.order,
                description: sourceForm.description,
                type: sourceForm.type,
                isTemplate: false,
                projectId: project._id,
                sectionId: newSection._id, // 首次关联到当前章节
                config: {
                  ...(sourceForm.config || {}),
                  fields: clonedFields,
                  lastUpdated: new Date(),
                },
              });
              await newForm.save();
              newFormId = newForm._id;
              codeToNewFormId.set(tplCode, newFormId);
            }

            // 将该表单加入当前章节的 forms（允许同一表单在多个访视下出现）
            newSection.forms.push(newFormId);
          }
          await newSection.save();
        }

        newConfigSections.push({
          sectionId: newSection._id,
          order: order || i + 1,
          config: sectionConfig || {}
        });
      }

      project.configSections = newConfigSections;
      await project.save();
    } else if (template && template.sections && template.sections.length > 0) {
      // 基于模板生成“项目专属”的章节与表单数据
      console.log('开始基于模板克隆章节与表单...');

      const newConfigSections = [];

      // 工具：生成唯一表单编码（全局唯一）
      const generateUniqueFormCode = (name = 'FORM') => {
        return `${name.toUpperCase().replace(/\s+/g, '_')}_${Date.now()}_${Math.floor(Math.random() * 10000)}`;
      };

      // 先遍历所有模板章节，基于模板表单code去重
      const codeToNewFormId = new Map();
      const codeToNewCode = new Map();

      for (let i = 0; i < template.sections.length; i++) {
        const templateSection = template.sections[i];
        // 读取模板章节
        const sectionDoc = await Section.findById(templateSection._id).populate({
          path: 'forms',
          model: 'Form',
        });

        if (!sectionDoc) {
          console.warn(`模板章节不存在: ${templateSection.name} (ID: ${templateSection._id})`);
          continue;
        }

        // 克隆章节（项目独立副本）
        const newSection = new Section({
          name: sectionDoc.name,
          order: i + 1,
          description: sectionDoc.description,
          forms: [],
          isTemplate: false,
          config: sectionDoc.config || {}
        });
        await newSection.save();

        // 克隆该章节下的表单（项目独立副本，按模板code去重）
        if (sectionDoc.forms && sectionDoc.forms.length > 0) {
          for (const sourceForm of sectionDoc.forms) {
            const tplCode = sourceForm.code || 'FORM';
            let newFormId = codeToNewFormId.get(tplCode);
            if (!newFormId) {
              // 第一次遇到该模板code，创建新表单
              let clonedFields = [];
              if (sourceForm.config && Array.isArray(sourceForm.config.fields)) {
                clonedFields = sourceForm.config.fields.map((f) => ({
                  ...JSON.parse(JSON.stringify(f)),
                  id: f.id || require('uuid').v4(),
                  metadata: {
                    createdAt: new Date(),
                    updatedAt: new Date(),
                    version: 1,
                  },
                }));
              }

              const mappedCode = codeToNewCode.get(tplCode) || generateUniqueFormCode('FORM');
              codeToNewCode.set(tplCode, mappedCode);

              const newForm = new Form({
                name: sourceForm.name,
                code: mappedCode,
                order: sourceForm.order,
                description: sourceForm.description,
                type: sourceForm.type,
                isTemplate: false,
                projectId: project._id,
                sectionId: newSection._id, // 首次关联为当前章节
                config: {
                  ...(sourceForm.config || {}),
                  fields: clonedFields,
                  lastUpdated: new Date(),
                },
              });
              await newForm.save();
              newFormId = newForm._id;
              codeToNewFormId.set(tplCode, newFormId);
            }

            // 将该表单加入当前章节
            newSection.forms.push(newFormId);
          }
          await newSection.save();
        }

        // 写入项目配置
        newConfigSections.push({
          sectionId: newSection._id,
          order: i + 1,
          config: {},
        });
      }

      // 更新项目中的章节引用为“新克隆”的章节
      project.configSections = newConfigSections;
      await project.save();

      console.log(`模板克隆完成: ${newConfigSections.length} 个章节（含表单）已生成并关联到项目`);
    }

    // 返回完整的项目信息
    await project.populate([
      {
        path: 'createdBy',
        select: 'username profile.firstName profile.lastName'
      },
      {
        path: 'configSections.sectionId',
        model: 'Section',
        select: 'name description isTemplate config'
      }
    ]);

    res.status(201).json({
      success: true,
      message: template ? '基于模板创建项目成功' : '项目创建成功',
      data: project
    });
  } catch (error) {
    console.error('创建项目失败:', error);
    
    if (error.code === 11000) {
      return res.status(400).json({
        success: false,
        message: '方案编号已存在'
      });
    }
    
    res.status(500).json({
      success: false,
      message: '创建项目失败',
      error: error.message
    });
  }
};

// 更新项目
const updateProject = async (req, res) => {
  try {
    const { id } = req.params;
    
    console.log('更新项目请求:', {
      id,
      body: req.body
    });

    // 先获取原项目信息（用于比较configSections变化）
    const originalProject = await Project.findById(id);
    if (!originalProject) {
      return res.status(404).json({
        success: false,
        message: '项目未找到'
      });
    }

    // 过滤掉不应该更新的字段
    const {
      _id,
      __v,
      createdBy,
      updatedBy,
      createTime,
      updateTime,
      isTemplate,
      ...allowedFields
    } = req.body;

    // 处理configSections字段的更新（如果存在）
    if (req.body.configSections && Array.isArray(req.body.configSections)) {
      const originalSectionIds = (originalProject.configSections || []).map(cs => cs.sectionId?.toString() || cs.toString());
      const newSectionIds = req.body.configSections.map(cs => cs.sectionId);

      // 找出新增的章节
      const addedSectionIds = newSectionIds.filter(sectionId => 
        !originalSectionIds.includes(sectionId.toString())
      );

      // 找出移除的章节
      const removedSectionIds = originalSectionIds.filter(originalId => 
        !newSectionIds.includes(originalId)
      );

      console.log('章节关联变化:', {
        原始章节: originalSectionIds,
        新章节: newSectionIds,
        新增: addedSectionIds,
        移除: removedSectionIds
      });

      // 验证新增的章节是否都存在（模板章节）
      if (addedSectionIds.length > 0) {
        const validSections = await Section.find({
          _id: { $in: addedSectionIds },
          isTemplate: true
        });
        
        if (validSections.length !== addedSectionIds.length) {
          return res.status(400).json({
            success: false,
            message: '部分章节不存在或不是模板章节'
          });
        }
        
        console.log('已验证新增章节:', validSections.map(s => ({ id: s._id, name: s.name })));
      }

      // configSections 已经是正确的格式，无需重新构建
      console.log('使用前端传递的configSections结构:', req.body.configSections.length, '个章节');
    }
    
    const updateData = {
      ...allowedFields,
      isTemplate: isTemplate,
      updatedBy: req.user._id
    };

    const project = await Project.findByIdAndUpdate(
      id,
      updateData,
      { new: true, runValidators: true }
    ).populate('createdBy updatedBy', 'username profile.firstName profile.lastName')
    .populate({
      path: 'configSections.sectionId',
      model: 'Section',
      select: 'name description isTemplate config'
    });

    console.log('更新后的项目:', {
      id: project._id,
      name: project.name,
      sectionsCount: project.configSections?.length || 0,
      sections: project.configSections?.map(cs => ({ sectionId: cs.sectionId, order: cs.order })) || []
    });

    res.json({
      success: true,
      message: '项目更新成功',
      data: project
    });
  } catch (error) {
    console.error('更新项目失败:', error);
    res.status(500).json({
      success: false,
      message: '更新项目失败',
      error: error.message
    });
  }
};

// 删除项目
const deleteProject = async (req, res) => {
  try {
    const { id } = req.params;

    // 检查项目是否存在
    const project = await Project.findById(id);
    if (!project) {
      return res.status(404).json({
        success: false,
        message: '项目未找到'
      });
    }

    // 删除关联的章节和表单
    await Section.deleteMany({ projectId: id });
    await Form.deleteMany({ projectId: id });
    
    // 删除项目
    await Project.findByIdAndDelete(id);

    res.json({
      success: true,
      message: '项目删除成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '删除项目失败',
      error: error.message
    });
  }
};

// 获取项目统计信息
const getProjectStats = async (req, res) => {
  try {
    const stats = await Project.aggregate([
      {
        $group: {
          _id: '$status',
          count: { $sum: 1 }
        }
      }
    ]);

    const total = await Project.countDocuments();

    res.json({
      success: true,
      data: {
        total,
        byStatus: stats.reduce((acc, item) => {
          acc[item._id] = item.count;
          return acc;
        }, {})
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取项目统计失败',
      error: error.message
    });
  }
};

// 获取项目前置页
const getProjectFrontMatter = async (req, res) => {
  try {
    const { id } = req.params;
    const project = await Project.findById(id).select('frontMatter');
    if (!project) {
      return res.status(404).json({ success: false, message: '项目未找到' });
    }
    // 统一按照 order 排序返回
    const frontMatter = (project.frontMatter || []).sort((a,b) => (a.order||0) - (b.order||0));
    res.json({ success: true, data: { frontMatter } });
  } catch (error) {
    res.status(500).json({ success: false, message: '获取前置页失败', error: error.message });
  }
};

// 更新项目前置页（完整替换）
const updateProjectFrontMatter = async (req, res) => {
  try {
    const { id } = req.params;
    const { frontMatter } = req.body || {};
    if (!Array.isArray(frontMatter)) {
      return res.status(400).json({ success: false, message: 'frontMatter 必须为数组' });
    }

    const project = await Project.findById(id);
    if (!project) {
      return res.status(404).json({ success: false, message: '项目未找到' });
    }

    // 校验 formId 存在且属于该项目（或允许跨访视，仅校验存在与可访问）
    const formIds = frontMatter.map(i => i.formId).filter(Boolean);
    const validForms = await Form.find({ _id: { $in: formIds } }).select('_id');
    if (validForms.length !== formIds.length) {
      return res.status(400).json({ success: false, message: '存在无效的表单ID' });
    }

    // 规范化与排序号写入
    const normalized = frontMatter.map((item, idx) => ({
      formId: item.formId,
      order: Number.isFinite(item.order) ? item.order : idx,
      showInToc: !!item.showInToc,
      tocLevel: [1,2].includes(item.tocLevel) ? item.tocLevel : 1,
      customTitle: item.customTitle || '',
      pageBreakAfter: item.pageBreakAfter !== false,
      hideFormTitle: item.hideFormTitle !== false // 默认隐藏标题
    }));

    // 保存
    project.frontMatter = normalized;
    await project.save();

    res.json({ success: true, message: '前置页已更新' });
  } catch (error) {
    res.status(500).json({ success: false, message: '更新前置页失败', error: error.message });
  }
};

module.exports = {
  getProjects,
  getProject,
  getProjectConfig,
  createProject,
  updateProject,
  deleteProject,
  getProjectStats,
  getProjectFrontMatter,
  updateProjectFrontMatter
};